package com.wdm.sms.commonutil.utils.jwt;

import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.wdm.sms.commonutil.config.exception.MyException;
import com.wdm.sms.entity.common.dto.user.token.UserTokenDTO;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: wudaiming
 * @date: 2023/3/13
 * @description: 整合JWT生成token
 * @version: 1.0
 */
@Slf4j
public class JwtTokenUtils {
    private static final Logger logger = LoggerFactory.getLogger(JWTUtil.class);

    //私钥
    private static final String TOKEN_SECRET = "123456";

    private JwtTokenUtils() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 生成token，自定义过期时间 毫秒
     *
     * @param user
     * @return
     */
    @PassToken
    public static String generateToken(UserTokenDTO user) {
        try {
            // 私钥和加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            // 设置头部信息
            Map<String, Object> header = new HashMap<>(2);
            header.put("Type", "Jwt");
            header.put("alg", "HS256");

            return JWT.create()
                    .withHeader(header)
                    //签收者
                    .withAudience(user.getName())
                    //主题
                    .withSubject("token")
                    .withClaim("token", JSONObject.toJSONString(user))
                    //2小时token过期
                    .withExpiresAt(DateUtil.offsetHour(new Date(),2))
                    //以TOKEN_SECRET作为token的密钥
                    .sign(algorithm);
        } catch (Exception e) {
            logger.error("generate token occur error, error is:{}", e);
            return null;
        }
    }

    /**
     * 检验token是否正确
     *
     * @param token
     * @return
     */
    public static UserTokenDTO parseToken(String token) {
        String tokenInfo="";
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //验证token
        JWTVerifier jwtVerifier = JWT.require(algorithm).build();
        try {
            DecodedJWT jwt = jwtVerifier.verify(token);
            tokenInfo = jwt.getClaim("token").asString();
        } catch (JWTVerificationException e) {
            throw new MyException(406, "权限验证失败！");
        }
        return JSON.parseObject(tokenInfo, UserTokenDTO.class);
    }
}